package com.base.common.processor;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import com.gitee.magic.core.utils.StringUtils;

/**
 * 
 * @author start
 *
 */
@Order(1)
public class BalancedIndexRedisStandaloneEnvironmentPostProcessor implements EnvironmentPostProcessor {

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		String active=environment.getRequiredProperty("spring.profiles.active");
		if(!"pro".equals(active)) {
			return;
		}
		System.out.println("loading balanced index active:"+active);
		String projectName=environment.getRequiredProperty("spring.application.name");
		
		String host=environment.getRequiredProperty("spring.data.redis.host");
		String username=environment.getProperty("spring.data.redis.username","");
		String password=environment.getRequiredProperty("spring.data.redis.password");
		Integer port=Integer.parseInt(environment.getRequiredProperty("spring.data.redis.port"));
		Integer database=Integer.parseInt(environment.getRequiredProperty("spring.data.redis.database"));
		
		RedisStandaloneConfiguration configuration=new RedisStandaloneConfiguration();
    	configuration.setHostName(host);
    	configuration.setPassword(password);
    	configuration.setPort(port);
    	if(!StringUtils.isEmpty(username)) {
    		configuration.setUsername(username);
    	}
    	configuration.setDatabase(database);
    	LettuceConnectionFactory connectionFactory=new LettuceConnectionFactory(configuration);
    	connectionFactory.afterPropertiesSet();
    	RedisTemplate<String,Integer> redisTemplate=new RedisTemplate<>();
		redisTemplate.setConnectionFactory(connectionFactory);
		redisTemplate.afterPropertiesSet();
		String key=projectName+"_"+active;
		Long kIndex=redisTemplate.opsForValue().increment(key);
		redisTemplate.expire(key, 1,TimeUnit.HOURS);
		connectionFactory.destroy();
		if(kIndex==null) {
			kIndex=0L;
		}
		Long dataCenterId=kIndex/32;
		Long workerId=kIndex%32;
		Properties props=new Properties();
		props.put("magic.system.balanced_worker_id", workerId);
		props.put("magic.system.balanced_datacenter_id", dataCenterId);

		environment.getPropertySources().addFirst(new PropertiesPropertySource("remote_balanced_index_config", props));
	}
	
}
